import router from './router'
import store from './store'
import { asyncRoutes } from '@/router/asyncRoutes'

const WHITE_LIST = ['/login', '/404']

// 处理一级路由权限数据
function getFirstRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    // item: parking:rule:list - 一级菜单:二级菜单:权限标识
    // 返回parking
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}

// 处理二级路由权限数据
function getSecondRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    // item: parking:rule:list - 一级菜单:二级菜单:权限标识
    // 返回parking:rule
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}

// 根据权限标识过滤路由表
function getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes) {
  // 对管理员权限进行特殊处理
  // 管理员一级权限：['*']
  if (firstRoutePerms.includes('*')) {
    return asyncRoutes
  }

  // 直接过滤掉没有一级路由权限的数据
  return asyncRoutes.filter(route => firstRoutePerms.includes(route.permission)).map(item => {
    // 对二级路由进行过滤
    return {
      ...item,
      children: item.children.filter(item => secondRoutePerms.includes(item.permission))
    }
  })
}

router.beforeEach(async(to, from, next) => {
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
      // 只有从来没有获取过权限数据 才执行后面的逻辑  store.state.user.userProfile.id
      if (!store.state.user.profile.id) {
        const permissions = await store.dispatch('user/getProfile')
        // 把后端的权限数组格式化为我们自己的两个权限数据
        // 一级路由权限数组
        const firstRoutePerms = getFirstRoutePerms(permissions)
        // 二级路由权限数组
        const secondRoutePerms = getSecondRoutePerms(permissions)
        // 最终有资格显示到左侧的所有路由表
        const routes = getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes)
        // addRoute动态添加
        for (const route of routes) {
          router.addRoute(route)
        }
        store.commit('menu/setMenuList', routes)
      }
    }
  } else {
    if (WHITE_LIST.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
